package game.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import common.config.exception.CustomException;
import common.model.enums.MilestoneUnlockTypeEnum;
import common.model.po.GBuilding;
import common.model.po.GItem;
import common.model.po.GMilestoneUnlock;
import game.mapper.GMilestoneUnlockMapper;
import game.model.converter.GMilestoneUnlockConverter;
import game.model.vo.MilestoneUnlockVo;
import game.service.GBuildingService;
import game.service.GItemService;
import game.service.GMilestoneUnlockService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 服务实现类
 *
 * @author 米泽鹏
 * @since 2024-01-19 下午 05:05
 */
@Service
public class GMilestoneUnlockServiceImpl extends ServiceImpl<GMilestoneUnlockMapper, GMilestoneUnlock> implements GMilestoneUnlockService {

	@Resource
	private GMilestoneUnlockMapper mapper;
	@Resource
	private GItemService itemService;
	@Resource
	private GBuildingService buildingService;

	@Override
	public List<MilestoneUnlockVo> getAllMilestoneUnlockVoByMilestoneId(Long milestoneId) {
		List<GMilestoneUnlock> unlockList = lambdaQuery().eq(GMilestoneUnlock::getMilestoneId, milestoneId).list();
		List<MilestoneUnlockVo> unlockVoList = Lists.newArrayListWithCapacity(unlockList.size());
		// 查询解锁项中的所有物品和建筑
		Set<Long> itemIdSet = unlockList.stream().filter(unlock -> unlock.getType() == MilestoneUnlockTypeEnum.ITEM).map(GMilestoneUnlock::getElementId).collect(Collectors.toSet());
		Set<Long> buildingIdSet = unlockList.stream().filter(unlock -> unlock.getType() == MilestoneUnlockTypeEnum.BUILDING).map(GMilestoneUnlock::getElementId).collect(Collectors.toSet());
		List<GItem> itemList = itemIdSet.isEmpty() ? Collections.emptyList() : itemService.listByIds(itemIdSet);
		List<GBuilding> buildingList = buildingIdSet.isEmpty() ? Collections.emptyList() : buildingService.listByIds(buildingIdSet);
		// 转换为vo（处理image字段）
		for (GMilestoneUnlock unlock : unlockList) {
			MilestoneUnlockVo milestoneUnlockVo = GMilestoneUnlockConverter.poToVo(unlock);
			MilestoneUnlockTypeEnum unlockType = unlock.getType();
			switch (unlockType) {
				case ITEM:
					GItem item = itemList.stream().filter(i -> i.getId().equals(unlock.getElementId())).findFirst().orElseThrow(() -> new CustomException("物品不存在"));
					milestoneUnlockVo.setImage(item.getImage());
					break;
				case BUILDING:
					GBuilding building = buildingList.stream().filter(i -> i.getId().equals(unlock.getElementId())).findFirst().orElseThrow(() -> new CustomException("建筑不存在"));
					milestoneUnlockVo.setImage(building.getImage());
					break;
				default:
					break;
			}
			unlockVoList.add(milestoneUnlockVo);
		}
		return unlockVoList;
	}

}
